package com.centriole.common.exception;

import com.centriole.common.utils.PaasResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(PaasException.class)
    public PaasResult paasExceptionHandler(PaasException exc){
        return new PaasResult(exc.getCode() ,exc.getMessage(),null);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public PaasResult handleIllegalParamException(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String message = "参数不合法";
        if (errors.size() > 0) {
            message = errors.get(0).getDefaultMessage();
        }
        PaasResult result = new PaasResult(400,"bad request",null);
        return result;
    }

    @ExceptionHandler(Exception.class)
    public PaasResult handleException(Exception e){
        e.printStackTrace();
        return new PaasResult(500,"inner error",null);
    }
}
